<template>
  <el-dialog
    width="380px"
    :title="$t('i18n.diaPhoto')"
    v-model="dialogPhotoVisible"
    :before-close="handleClose" 
  >
    <div class="crop-demo">
      <div class="crop-demo-btn">
        <el-avatar :size="150" :src="cropImg"></el-avatar>
        <input
          class="crop-input"
          type="file"
          name="image"
          accept="image/*"
          @change="setImage"
        />
      </div>
    </div>
    <el-dialog
      :title="$t('i18n.croppic')"
      v-model="dialogVisible"
      width="600px"
    >
      <vue-cropper
        ref="cropper1"
        :src="imgSrc"
        style="width:100%;height:300px;"
      ></vue-cropper>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            :size="'small'"
            type="danger"
            icon="el-icon-back"
            @click="cancelCrop"
            >取 消</el-button
          >
          <el-button
            type="primary"
            :size="'small'"
            icon="el-icon-check"
            @click="confirmCrop"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <template #footer>
      <span class="dialog-footer">
        <el-button
          :size="'small'"
          type="danger"
          icon="el-icon-back"
          @click="handleClose"
          >{{ $t("table.Global_Cancel") }}</el-button
        >
        <el-button
          :size="'small'"
          type="primary"
          icon="el-icon-check"
          @click="confirm"
          >{{ $t("table.Global_Save") }}</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
<style lang="less">
.content-title {
  font-weight: 400;
  line-height: 50px;
  margin: 10px 0;
  font-size: 22px;
  color: #1f2f3d;
}

.pre-img {
  width: 150px;
  height: 150px;
  background: #f8f8f8;
  border: 1px solid #eee;
  border-radius: 50px;
}
.crop-demo {
  display: flex;
  align-items: flex-end;
}
.crop-demo-btn {
  position: relative;
  width: 150px;
  height: 150px;
  line-height: 40px;
  font-size: 14px;
  border-radius: 50px;
  box-sizing: border-box;
  left: 100px;
}
.crop-input {
  position: absolute;
  width: 150px;
  height: 150px;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}
</style>
<script>
import VueCropper from "vue-cropperjs";
import "cropperjs/dist/cropper.css";
import reqVue from "../utils/req.vue";
import confVue from "../utils/conf.vue";
export default {
  emits: ["loadphoto"],
  data() {
    return {
      dialogPhotoVisible: false,
      cropImg: require("../assets/img/img.jpeg"),
      dialogVisible: false,
      way: confVue.$docApi,
      filename: "",
      photoid: 0,
      isfrom: false,
      fieldKey: "",
    };
  },
  components: {
    VueCropper,
  },
  methods: {
    ///加载要裁剪的图片
    setImage(e) {
      const file = e.target.files[0];
      if (!file.type.includes("image/")) {
        return;
      }
      this.filename = file.name;
      const reader = new FileReader();
      reader.onload = (event) => {
        this.dialogVisible = true;
        this.imgSrc = event.target.result;
        this.$refs.cropper1 && this.$refs.cropper1.replace(event.target.result);
      };
      reader.readAsDataURL(file);
    },
    ///画制图片
    cropImage() {
      this.cropImg = this.$refs.cropper1.getCroppedCanvas().toDataURL();
    },
    ///取消
    cancelCrop() {
      this.dialogVisible = false;
    },
    ///保存图片
    confirmCrop(type) {
      console.log("finish", type);
      let formData = new FormData();
      let blobs = this.dataURItoBlob(
        this.$refs.cropper1.getCroppedCanvas().toDataURL()
      );
      this.cropImage();
      formData.append("file", blobs, this.filename);
      reqVue
        .$Post(
          formData,
          "file/v1.0/upload/0",
          this.way,
          "application/x-www-form-urlencoded"
        )
        .then(
          function(data) {
            if (data.status) {
              this.photoid = data.body;
              this.dialogVisible = false;
            } else {
              this.$message.error(data.message);
            }
          }.bind(this)
        );
    },
    ///将base64转换称blob
    dataURItoBlob(dataURI) {
      // base64 解码
      let byteString = window.atob(dataURI.split(",")[1]);
      let mimeString = dataURI
        .split(",")[0]
        .split(":")[1]
        .split(";")[0];
      let ab = new ArrayBuffer(byteString.length);
      let ia = new Uint8Array(ab);
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ab], { type: mimeString });
    },
    ////取消后删除文件
    handleClose() {
      reqVue.$Post([this.photoid], "file/v1.0/uploaddel", this.way).then(
        function(data) {
          if (!data.status) {
            this.tableLoading = false;
            this.$message.error(data.message);
          } else {
            this.photoid = 0;
            this.dialogPhotoVisible = false;
          }
        }.bind(this)
      );
    },
    ///确定后事件
    confirm() {
      if (this.photoid >= 0 && !this.isfrom) {
        reqVue
          .$Post(null, "file/v1.0/savephoto/" + this.photoid + "/0", this.way)
          .then(
            function(data) {
              if (!data.status) {
                this.$message.error(data.message);
              } else {
                this.photoid = 0;
                this.$emit("loadphoto", this.cropImg);
                this.dialogPhotoVisible = false;
              }
            }.bind(this)
          );
      } else {
        this.$emit("loadphoto", {
          photo: this.cropImg,
          photoid: this.photoid,
          fieldKey: this.fieldKey,
        });
        this.dialogPhotoVisible = false;
        this.photoid = 0;
      }
    },
  },
};
</script>
